import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

export async function DELETE(
  req: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const userid = await getUser(req)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }
    const scriptDB = await prisma.vms_script.findUnique({
      where: { id: params.id }
    })
    
    if (!scriptDB) {
      return NextResponse.json(
        { error: '未找到脚本' },
        { status: 404 }
      )
    }
    
    // 检查当前用户是否有权限删除
    if (scriptDB.user_id !== userid) {
      return NextResponse.json(
        { error: '无权删除他人脚本' },
        { status: 403 }
      )
    }
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        script_count: {
          decrement: 1
        }
      }
    })

    const script = await prisma.vms_script.delete({
      where: {
        id: params.id
      }
    })

    return NextResponse.json(script)
  } catch (error) {
    console.error('[SCRIPT_DELETE]', error)
    return NextResponse.json(
      { error: 'Internal Error' },
      { status: 500 }
    )
  }
}
